package com.luoye.lj.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User:
 * Date: 15-11-4
 * Time: 下午8:52
 * To change this template use File | Settings | File Templates.
 */
public class UrlRecordInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(UrlRecordInterceptor.class);

    private List<String> ignoredRequestMappings;

    public List<String> getIgnoredRequestMappings() {
        return ignoredRequestMappings;
    }

    public void setIgnoredRequestMappings(List<String> ignoredRequestMappings) {
        this.ignoredRequestMappings = ignoredRequestMappings;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl=httpServletRequest.getRequestURL().toString();
        try {
            if (o instanceof HandlerMethod) {
                String requestMapping=getRequestMapping((HandlerMethod)o);
                logger.debug("requestMapping->" + requestMapping);
                if(!matchIgnore(requestMapping)) {
                    logger.debug("not match ignore");

                    Method method = ((HandlerMethod) o).getMethod();
                    if (!method.isAnnotationPresent(ResponseBody.class)) {//没有ResponseBody注解，则记录url
                        logger.debug("not ResponseBody");
                        writeCookie(httpServletResponse,requestUrl);
                        //httpServletRequest.setAttribute("requestUrl",requestUrl);
                    } else {
                        logger.debug("ResponseBody");
                    }
                }
            }
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
        }
        return true;
    }
    private void writeCookie(HttpServletResponse httpServletResponse,String requestUrl){
        Cookie cookie=new Cookie("requestUrl",requestUrl);
        cookie.setMaxAge(60*60);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
    }
    private String getRequestMapping(HandlerMethod handlerMethod){
        String requestMapping="";

        Class beanType=handlerMethod.getBeanType();
        if(beanType.isAnnotationPresent(RequestMapping.class)){
            RequestMapping requestMappingObject= (RequestMapping) beanType.getAnnotation(RequestMapping.class);
            String[] mappings=requestMappingObject.value();
            if(mappings!=null&&mappings.length>0) {
                requestMapping += requestMappingObject.value()[0];
            }
        }

        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping requestMappingObject = method.getAnnotation(RequestMapping.class);
            String[] mappings=requestMappingObject.value();
            if(mappings!=null&&mappings.length>0) {
                requestMapping += requestMappingObject.value()[0];
            }
        }

        return requestMapping;
    }

    private boolean matchIgnore(String requestMapping){
        if(!CollectionUtils.isEmpty(this.ignoredRequestMappings)){
            for(String ignoredRequestMapping:ignoredRequestMappings){
                if(ignoredRequestMapping.indexOf("*")!=-1){
                    ignoredRequestMapping=ignoredRequestMapping.replaceAll("\\*","");
                    if(requestMapping.startsWith(ignoredRequestMapping)){
                        return true;
                    }
                }else if(requestMapping.equals(ignoredRequestMapping)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private String getClientIp(HttpServletRequest request){
        String clientIp="";
        /*****获取外网ip********/
        if (!StringUtils.isEmpty(request.getHeader("X-Forwarded-For")))
            clientIp = request.getHeader("X-Forwarded-For");
        else if(!StringUtils.isEmpty(request.getHeader("X-Real-IP")))
            clientIp = request.getHeader("X-Real-IP");
        else
            clientIp = "0.0.0.0";

        /********获取内网ip**********/
        String vcip= request.getRemoteAddr();
        if(vcip==null||vcip==""){
            clientIp=clientIp+"."+"0.0.0.0";
        }else{
            clientIp=clientIp+"."+vcip;
        }
        //println "clientIp: "+clientIp
        return clientIp;
    }
}
